import type { Notice } from 'shared-types'
import { useController } from './controller'

export async function initNotices() {
  const controller = useController()
  let noticeQueue: Notice[] = []

  try {
    const notices = await controller.listNotices()
    noticeQueue = notices.list
    readNotices(noticeQueue, controller)

    controller.onNotice((notice) => {
      noticeQueue.push(notice)
      readNotices(noticeQueue, controller)
    })
  } catch (err) {
    console.error(err)
  }
}

async function readNotices(notices: Notice[], controller: ReturnType<typeof useController>) {
  if (notices.length === 0) {
    return
  }
  await controller.readNotice(notices.pop()!)
  readNotices(notices, controller)
}
